
package SoulRandAttr

import(
	"fmt"
	"sanguo/node/table/excel"
	"sanguo/node/table/excel/table"
	"strconv"

	"github.com/tealeg/xlsx"
)

func readInt32(v string) int32 {
	return int32(readFloat(v))
}

func readFloat(v string) float64 {
	vv,err := strconv.ParseFloat(v,64)
	if nil != err {
		panic(err)
	}
	return vv
}

func readBool(str string) bool {
    b, err := strconv.ParseBool(str)
	if nil != err {
		panic(err)
	}
    return b
}

func readStr(v string) string {
	return fmt.Sprintf("%s",v)
}

type RandAttr_ struct {
	Prob int32
}

type SoulRandAttr struct {
	ID int32
	Pos int32
	Order int32
	Count int32
	RandAttr []RandAttr_
}

func readAddRandAttr(names, row *xlsx.Row) []RandAttr_ {
			
	RandAttr := make([]RandAttr_,0)
	r := excel.RowSplit("4;5;6;7;8;9;10;11;12")
	_, err := strconv.ParseFloat(r[0][0], 64)
	
	if err == nil {		
		for _,v := range(r) {
			RandAttr_ := RandAttr_{}

			RandAttr_.Prob = readInt32(row.Cells[readInt32(v[0])].String())
				
			RandAttr = append(RandAttr,RandAttr_)
		}
	} else {
		for i := readInt32(r[1][0]); i <= readInt32(r[1][1]); i++ {
			RandAttr_ := RandAttr_{}

			RandAttr_.Prob = readInt32(row.Cells[getIdxByName(names, fmt.Sprintf("%s%d", r[0][0], i))].String())
				
			RandAttr = append(RandAttr,RandAttr_)
		}
	}
	return RandAttr
}

type Table struct {
	IDMap map[int32]*SoulRandAttr
	tmpIDMap map[int32]*SoulRandAttr
	xlsxName string
}

var Table_ Table

func getIdxByName(names *xlsx.Row, name string) int {
	for i, v := range names.Cells {
		if v.String() == name {
			return i
		}
	}
	return -1
}

func init() {
	Table_.xlsxName = "SoulRandAttr.xlsx"
	Table_.IDMap = make(map[int32]*SoulRandAttr)
	Table_.tmpIDMap = make(map[int32]*SoulRandAttr)

	table.AddTable(&Table_)
}


func (this *Table) Load(path string) {

	excel.EmptyFunc()

    xlFile, err := xlsx.OpenFile(path + this.xlsxName)
    if err != nil {
		panic(err)
    }

    sheet := xlFile.Sheets[0]
    names := sheet.Rows[1]
    rows  := sheet.Rows[3:]

    for _,row := range(rows) {
    	if len(row.Cells) > 0 && row.Cells[0].String() != "" {
    		ele := &SoulRandAttr{}
    	
		ele.ID = readInt32(row.Cells[getIdxByName(names, "ID")].String())
		this.tmpIDMap[ele.ID] = ele
		ele.Pos = readInt32(row.Cells[getIdxByName(names, "Pos")].String())
		ele.Order = readInt32(row.Cells[getIdxByName(names, "Order")].String())
		ele.Count = readInt32(row.Cells[getIdxByName(names, "Count")].String())
		ele.RandAttr = readAddRandAttr(names, row)

		}
    }

    this.IDMap = this.tmpIDMap
 
}

